/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.anniversary.rest;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.anniversary.domain.Department;
import me.zhengjie.modules.anniversary.service.DepartmentService;
import me.zhengjie.modules.anniversary.service.dto.DepartmentDto;
import me.zhengjie.modules.anniversary.service.dto.DepartmentQueryCriteria;
import me.zhengjie.utils.PageUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
* @website https://el-admin.vip
* @author Jiayin Wei
* @date 2020-07-22
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "院系架构管理")
@RequestMapping("/api/department")
public class DepartmentController {

    private final DepartmentService departmentService;
    private static final String ENTITY_NAME = "department";

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('department:list')")
    public void download(HttpServletResponse response, DepartmentQueryCriteria criteria) throws Exception {
        departmentService.download(departmentService.queryAll(criteria, false), response);
    }

    @GetMapping
    @Log("查询院系架构")
    @ApiOperation("查询院系架构")
    @PreAuthorize("@el.check('department:list')")
    public ResponseEntity<Object> query(DepartmentQueryCriteria criteria) throws Exception{
        List<DepartmentDto> departmentDtos = departmentService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(departmentDtos, departmentDtos.size()), HttpStatus.OK);
    }

    @GetMapping("/tree")
    @Log("查询院系架构")
    @ApiOperation("查询院系架构")
    @PreAuthorize("@el.check('department:list')")
    public ResponseEntity<Object> queryByTree(DepartmentQueryCriteria criteria) throws Exception{
        List<DepartmentDto> departmentDtos = departmentService.queryAll(criteria, true);
        return new ResponseEntity<>(departmentService.buildTree(new ArrayList<>(departmentDtos)), HttpStatus.OK);
    }

    @Log("查询已添加院系架构的可选年份")
    @GetMapping("/years")
    @ApiOperation("查询已添加院系架构的可选年份")
    @PreAuthorize("@el.check('department:list')")
    public ResponseEntity<Object> getDepartmentYears() {
        return new ResponseEntity<>(departmentService.getDepartmentYears(), HttpStatus.OK);
    }

    //@AnonymousAccess
    @Log("按照年份获取专业")
    @GetMapping("/major/{year}")
    @ApiOperation("按照年份获取专业")
    @PreAuthorize("@el.check('department:list')")
    public ResponseEntity<Object> getMajors(@PathVariable Integer year) {
        return new ResponseEntity<>(departmentService.getMajors(year), HttpStatus.OK);
    }

    @Log("查询部门")
    @ApiOperation("查询部门:根据ID获取同级与上级数据")
    @PostMapping("/superior")
    @PreAuthorize("@el.check('department:list')")
    public ResponseEntity<Object> getSuperior(@RequestBody List<Long> ids) {
        Set<DepartmentDto> departmentDtos  = new LinkedHashSet<>();
        for (Long id : ids) {
            DepartmentDto departmentDto = departmentService.findById(id);
            List<DepartmentDto> departments = departmentService.getSuperior(departmentDto, new ArrayList<>());
            departmentDtos.addAll(departments);
        }
        return new ResponseEntity<>(departmentService.buildTree(new ArrayList<>(departmentDtos)), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增院系架构")
    @ApiOperation("新增院系架构")
    @PreAuthorize("@el.check('department:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Department resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        departmentService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改院系架构")
    @ApiOperation("修改院系架构")
    @PreAuthorize("@el.check('department:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Department resources){
        departmentService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除院系架构")
    @ApiOperation("删除院系架构")
    @PreAuthorize("@el.check('department:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        Set<DepartmentDto> departmentDtos = new HashSet<>();
        for (Long id : ids) {
            List<Department> departmentList = departmentService.findByParentId(id);
            departmentDtos.add(departmentService.findById(id));
            if(CollectionUtil.isNotEmpty(departmentList)){
                departmentDtos = departmentService.getDeleteDepts(departmentList, departmentDtos);
            }
        }
        departmentService.delete(departmentDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}